package com.yloveg.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;
import com.yloveg.base.BaseController;
import com.yloveg.common.FreemarkUtil.OrderStatus;
import com.yloveg.common.FreemarkUtil.PaymentType;
import com.yloveg.common.FreemarkUtil.YesOrNo;
import com.yloveg.common.PageUtil;
import com.yloveg.common.PayUtil;
import com.yloveg.common.WlUtil;
import com.yloveg.entity.PaymentConfigure;
import com.yloveg.entity.ProductContent;
import com.yloveg.entity.ShopAddress;
import com.yloveg.entity.ShopCart;
import com.yloveg.entity.ShopCartExtend;
import com.yloveg.entity.ShopOrders;
import com.yloveg.service.PaymentConfigureService;
import com.yloveg.service.ShopAddressService;
import com.yloveg.service.ShopCartService;
import com.yloveg.service.ShopOrdersService;

@Controller
@RequestMapping({"/order"})
public class OrderController extends BaseController {  
	
    @Autowired
    private ShopOrdersService shopOrdersService;
    
    @Autowired
    private ShopCartService shopCartService;
    
    @Autowired
    private ShopAddressService shopAddressService;
    
    @Autowired
    private PaymentConfigureService paymentConfigureService;
    
    /**
     * 确认订单页面
     * @param cartId
     * @param map
     * @return
     */
    @RequestMapping({"/orderConfirm"})  
    public String orderConfirm(String cartId,ModelMap map){
    	String[] arr = cartId.split(","); 
    	Map<String, Object> tempMap = new HashMap<String, Object>();
    	tempMap.put("ids", arr);
    	List<ShopCartExtend> cartList = shopCartService.selectExtendByTerm(tempMap);
    	//创建订单
    	Double amount =0d;
    	Long shopId = 0l;
    	for (ShopCartExtend shopCartExtend : cartList) {
    		shopId = shopCartExtend.getShopId();
    		amount+=shopCartExtend.getProductNum()*Double.valueOf(shopCartExtend.getProductPrice());
		}
    	ShopOrders order = new ShopOrders();
    	order.setOrderAmount(amount);
    	order.setCartId(cartId.toString());
    	order.setOrderStatus(OrderStatus.TOBECONFIRM.getValue());
    	order.setUserId(this.getSessionUser().getId());
    	order.setShopId(shopId);
    	shopOrdersService.insertOrder(order);
    	map.put("orderId",order.getId());
    	ShopAddress temp = new ShopAddress();
    	temp.setUserId(this.getSessionUser().getId());
    	List<ShopAddress> addList= shopAddressService.selectByTerm(temp);
    	temp.setIsDefault(YesOrNo.YES.getValue());
    	List<ShopAddress> tempList= shopAddressService.selectByTerm(temp);
    	if(tempList.size()>0){
    		map.put("add",tempList.get(0));
    	}else if(addList.size()>0){
    		map.put("add",addList.get(0));
    	}else{
    		map.put("add","0");
    	}
    	map.put("addList",addList);
    	map.put("car",cartList);
    	map.put("cartId",cartId);
        return "landing/order/orderConfirm";
    }
    
    /**
     * 结算
     * @param cartId
     * @param map
     * @return
     * @throws Exception 
     */
    @RequestMapping({"/orderSettlement"}) 
    public void orderSettlement(String cartId,Long addressId,Long orderId,ModelMap map,HttpServletRequest request, HttpServletResponse response) throws Exception{
    	if(cartId!=null||addressId!=null){
        	if(addressId!=null) {
            	ShopOrders order = shopOrdersService.selectByPrimaryKey(orderId);
            	order.setAddressId(addressId);
            	order.setOrderStatus(OrderStatus.PENDINGPAY.getValue());
            	shopOrdersService.updateByPrimaryKeySelective(order);   		
        	}
        	//更改购物车状态
        	ShopCart cart = new ShopCart();
        	String[] arr = cartId.split(","); 
        	cart.setCartStatus(YesOrNo.YES.getValue());
        	for (String cid : arr) {
        		cart.setId(Long.valueOf(cid));
        		shopCartService.updateByPrimaryKeySelective(cart);
    		}    		
    	}
    	new PayUtil().goWebAlipay(shopOrdersService.selectByPrimaryKey(orderId), paymentConfigureService.selectByPrimaryKey(32L), request, response);
    }
    
    //购物车页面
    @RequestMapping({"/shopCart"})  
    public String shopCart(ModelMap map){
    	Map<String, Object> parMap = new HashMap<String, Object>();
    	parMap.put("userId", this.getSessionUser().getId());    
    	parMap.put("cartStatus", YesOrNo.NO.getValue());
    	map.put("car", shopCartService.selectCartWidthShop(parMap));
        return "landing/order/shopCart";
    }
    //更改购物车数值
    @RequestMapping("/chooseCartNum")
    @ResponseBody
    public Map<String, Object> chooseCartNum(Long cartId,String type){
        ShopCart cart = new ShopCart();
        cart.setId(cartId);
        cart = shopCartService.selectOne(cart);
        if(type.equals("add")){
        	cart.setProductNum(cart.getProductNum()+1);
        }else{
        	cart.setProductNum(cart.getProductNum()-1);
        }
        shopCartService.updateByPrimaryKeySelective(cart);
    	Map<String, Object> map = new HashMap<String, Object>();
    	map.put("code", "1");
    	map.put("msg", "操作成功");;
        return map;
    }
        
    //删除购物车
    @RequestMapping("/deleteCart")
    @ResponseBody
    public Map<String, Object> deleteCart(@RequestParam(value = "cartId[]", required = false) List<Long> cartId){
        ShopCart cart = new ShopCart();
        cart.setState(0);
    	for (Long id : cartId) {
    		cart.setId(id);
    		shopCartService.updateByPrimaryKeySelective(cart);
	   }
    	Map<String, Object> map = new HashMap<String, Object>();
    	map.put("code", "1");
    	map.put("msg", "删除成功");
        return map;
    }
    //所有订单页面
    @RequestMapping({"/allOrder"})  
    public String allOrder(ModelMap map){
        return "landing/order/allOrder";
    } 
    //待付款订单页面
    @RequestMapping({"/pendingPayOrder"})  
    public String pendingPayOrder(ModelMap map){
    	map.put("orderStatus", OrderStatus.PENDINGPAY.getValue());
        return "landing/order/pendingPayOrder";
    }
    //待发货订单页面
    @RequestMapping({"/toBeShippedOrder"})  
    public String toBeShippedOrder(ModelMap map){
    	map.put("orderStatus", OrderStatus.TOBESHIPPED.getValue());
        return "landing/order/toBeShippedOrder";
    }
    //待收货订单页面
    @RequestMapping({"/toBeReceivedOrder"})  
    public String toBeReceivedOrder(ModelMap map){
    	map.put("orderStatus", OrderStatus.TOBERECEIVED.getValue());
        return "landing/order/toBeReceivedOrder";
    }
    //已完成订单页面
    @RequestMapping({"/completedOrder"})  
    public String completedOrder(ModelMap map){
    	map.put("orderStatus", OrderStatus.TOBEEVALUATED.getValue());
        return "landing/order/completedOrder";
    }
    //查询订单
    @RequestMapping("/queryOrderPage")
    @ResponseBody
    public Map<String, Object> queryOrderPage(int page, int limit,ShopOrders record){
    	record.setUserId(this.getSessionUser().getId());
        Map<String, Object> map = PageUtil.dateToLayTable(shopOrdersService.queryOrdersPage(page, limit, record));
        return map; 
    }
    //编辑订单
    @RequestMapping("/editOrder")
    @ResponseBody
    public Map<String, Object> editOrder(ShopOrders order){
    	 Map<String, Object> map = new HashMap<String, Object>();
    	if(order.getId()!=null){
    		shopOrdersService.updateByPrimaryKeySelective(order);
    		map.put("code", "1");
    		map.put("msg", "操作成功");
    		return map; 
    	}else{
    		map.put("code", "0");
    		map.put("msg", "操作失败，请稍后再试！");
    		return map; 
    	}
    } 
    
    //微信转账支付订单
    @RequestMapping("/wxzzOrder")
    @ResponseBody
    public Map<String, Object> wxzzOrder(String cartId,ShopOrders order){
    	//更改购物车状态
    	ShopCart cart = new ShopCart();
    	String[] arr = cartId.split(","); 
    	cart.setCartStatus(YesOrNo.YES.getValue());
    	for (String cid : arr) {
    		cart.setId(Long.valueOf(cid));
    		shopCartService.updateByPrimaryKeySelective(cart);
		}  
    	Map<String, Object> map = new HashMap<String, Object>();
    	if(order.getId()!=null){
    		order.setPaidWay(PaymentType.WXZZ.getValue());
    		order.setPaidTime(new Date());
    		order.setOrderStatus(OrderStatus.TOBESHIPPED.getValue());
    		shopOrdersService.updateByPrimaryKeySelective(order);
    		map.put("code", "1");
    		map.put("msg", "操作成功");
    		return map; 
    	}else{
    		map.put("code", "0");
    		map.put("msg", "操作失败，请稍后再试！");
    		return map; 
    	}
    }  
    
    //查看物流信息
	@RequestMapping({"/lookWl"})  
	public String lookWl(ModelMap map,ShopOrders order){
    	PageInfo<ShopOrders> pageList = shopOrdersService.queryOrdersPage(1,10,order);
    	List<ShopOrders> tempList = pageList.getList();
    	map.put("order", tempList.get(0));
    	if(tempList.get(0).getCourierNumber()!=null){
    		map.addAllAttributes(WlUtil.getWl(tempList.get(0).getCourierNumber().toString(), tempList.get(0).getCourierCom()));
    	}
	    return "landing/order/lookWl";
	}
	
	

}
